package oas.web;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import oas.db.UserRepository;
import oas.db.WorkcellRepository;
import oas.db.jdbc.JdbcWorkcellRepository;
import oas.domain.User;
import oas.domain.Workcell;

/**
 * 部门页面控制类
 *
 * @author 97496
 * @version v1.2.0
 */
@Controller
@RequestMapping("/workcells")
@SessionAttributes("parentWorkcell")
public class WorkcellsController {

    private final static Log log = LogFactory.getLog(JdbcWorkcellRepository.class);

    @Autowired
    private WorkcellRepository workcellRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 显示子部门列表及功能
     *
     * @param pageNo   起始页面
     * @param pageSize 页面大小
     * @param model    model
     * @return 子部门列表
     */
    @RequestMapping(method = RequestMethod.GET)
    public String workcells(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                            @RequestParam(value = "pageSize", defaultValue = "8") int pageSize, Model model,
                            HttpSession session) {
        Long id = ((User) session.getAttribute("user")).getWorkcell().getId();

        Workcell workcell = workcellRepository.findById(id);

        PaginationSupport<Workcell> ps = workcellRepository.findWorkcells(workcell, pageNo, pageSize);
        model.addAttribute("paginationSupport", ps);
        model.addAttribute("parentWorkcell", workcell);
        model.addAttribute("size", ps.getItems().size());
        //System.out.println("ps.getItems().size()"+ps.getItems().size());
        /*
         * List<Workcell> workcells=workcell.getChildWorkcells();
         * session.setAttribute("workcells", workcells);
         */

        return "workcells";

    }

    /**
     * @param pageNo     起始页面
     * @param pageSize   页面大小
     * @param workcellId 部门id
     * @param model      model
     * @return 子部门列表
     */
    @RequestMapping(value = "/childrenWorkcells", method = RequestMethod.GET)
    public String workcellsChildren(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                    @RequestParam(value = "pageSize", defaultValue = "8") int pageSize,
                                    @RequestParam(value = "workcellId", defaultValue = "1") Long workcellId,
                                    Model model, HttpSession session) {
        Long id = workcellId;
        //Long parentWorkcellId = workcellRepository.findParentById(id).getId();


        Workcell workcell = workcellRepository.findById(id);

        //Workcell parentWorkcell = workcellRepository.findById(parentWorkcellId);
        PaginationSupport<Workcell> ps = workcellRepository.findWorkcells(workcell, pageNo, pageSize);

        //PaginationSupport<Workcell> parentps = workcellRepository.findWorkcells(parentWorkcell, pageNo, pageSize);
        model.addAttribute("paginationSupport", ps);
        model.addAttribute("parentWorkcell", workcell);
        model.addAttribute("size", ps.getItems().size());

        User user = (User) session.getAttribute("user");

        if (user.getWorkcell().getId().equals(workcellRepository.findParentById(id).getId())) {
            return "workcells";
        } else {
            String parentUrl = "/workcells/childrenWorkcells";
            parentUrl = "/workcells/childrenWorkcells?workcellId=" + workcellRepository.findParentById(id).getId();
            model.addAttribute("parentUrl", parentUrl);
            return "workcellsChildren";
        }
    }

    /**
     * 增加部门页面
     *
     * @param model model
     * @return 添加部门页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String showAdd(Model model) {
        model.addAttribute(new Workcell());
        return "addWorkcell";
    }

    /**
     * 将部门添加到数据库
     *
     * @param workcell 新增的部门
     * @param model    model
     * @param session  HTTP Session
     * @return 添加结果
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addWorkcell(Workcell workcell, Model model, HttpSession session) {

        Workcell parentWorkcell = (Workcell) session.getAttribute("parentWorkcell");
        workcell.setAvailable(true);
        workcell = workcellRepository.addWorkcell(workcell, parentWorkcell);
        model.addAttribute(workcell);
        return "addWorkcellSuccessful";
    }

    /**
     * 显示可删除部门列表
     *
     * @param pageNo   起始页面
     * @param pageSize 页面大小
     * @param session  HTTP Session
     * @return 删除结果
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String showDelete(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(value = "pageSize", defaultValue = "8") int pageSize, HttpSession session) {
        Long id = ((User) session.getAttribute("user")).getWorkcell().getId();
        Workcell workcell = workcellRepository.findById(id);
        session.setAttribute("paginationSupport", workcellRepository.findWorkcells(workcell, pageNo, pageSize));
        return "deleteWorkcell";
    }

    /**
     * 删除部门
     *
     * @param id      部门id
     * @param session HTTP Session
     * @return 删除结果
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteWorkcell(@PathVariable("id") Long id, HttpSession session) {
        Workcell workcell = workcellRepository.findById(id);
        workcellRepository.deleteWorkcell(workcell);
        return "deleteWorkcellSuccessful";
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String showUpdate(Model model) {
        model.addAttribute(new Workcell());
        return "updateWorkcell";
    }

    /**
     * 更新部门信息
     *
     * @param workcell 新部门信息
     * @param errors   输入错误
     * @return 更新结果
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateWorkcell(@Valid Workcell workcell, Errors errors) {
        if (errors.hasErrors()) {
            return "updateWorkcell";
        }
        Long workcellId = workcell.getId();
        if (workcellRepository.findById(workcellId) == null) {
            return "updateWorkcellFaild";
        } else {
            workcellRepository.updateWorkcell(workcell);
            return "updateWorkcellSuccessful";
        }
    }
}
